# -*- coding: utf-8 -*-
import os
import time,json
import subprocess
import sys
import random
import uuid
import re
import base64


def exec_cmd(cmd_str, shell=True, stdout=subprocess.PIPE):
    p = subprocess.Popen(cmd_str, shell=shell, stdout=stdout, stderr=subprocess.PIPE)
    # out,err = p.communicate()
    return p.communicate()


def get_sig_info(cmd_str):
    out, err = exec_cmd(cmd_str)
    if err:
        return err
    else:
        try:
            return out.splitlines()[0].strip()
        except:
            return ""


def randmac(hx=None):
    Maclist = []
    for i in range(1,6 if hx else 7):
        RANDSTR = "".join(random.sample("0123456789abcdef",2))
        Maclist.append(RANDSTR)
    randmac = "{}:{}".format(hx,":".join(Maclist)) if hx else ":".join(Maclist)
    return randmac

def random_number(num2):
    list2 = []
    for number in range(num2):
        str2 = str(random.randint(0, 9))
        list2.append(str2)
    b = " ".join(list2).replace(" ", "")
    return b


cf = """
bootdisk: scsi0
cores: 12
cpu: host
hostpci0: 01:11.2,pcie=1
machine: q35
memory: 30720
name: jxdxxy-206
net0: virtio=5A:E1:51:78:1A:D3,bridge=vmbr0
numa: 1
onboot: 1
ostype: l26
scsi0: local-lvm:vm-1206-disk-0,serial=CVCV693551LB120BGN,size=70G,ssd=1
scsi1: /dev/disk/by-id/scsi-35000c500583452cf,size=2930266584K
scsi2: /dev/disk/by-id/scsi-35000c500b6e328db,size=2930266584K
scsi3: /dev/disk/by-id/scsi-35000c50057ca8a27,size=2930266584K
scsi4: /dev/disk/by-id/scsi-35000c5005833aa47,size=2930266584K
scsi5: /dev/disk/by-id/scsi-35000c50058346713,size=2930266584K
scsi6: /dev/disk/by-id/scsi-35000c500b6e6ee23,size=2930266584K
scsihw: virtio-scsi-pci
smbios1: base64=1,manufacturer=RGVsbCBJbmM=,product=UG93ZXJFZGdlIFI3MjB4ZA==,serial=OUlPWE04Sw==,uuid=3c5a1c92-ee4c-4dcb-acbb-c94595cd7cea,version=Tm90IFNwZWNpZmllZA==
sockets: 2
vmgenid: 93521386-35d2-424b-abc4-98fae6781ad4

"""
if __name__=="__main__":
    # 替换配置文件
    # CVCV693551LB120BGN
    cfg_r = dict()
    hostname = get_sig_info('hostname')
    # if len(sys.argv) != 3:
    #     print("需要两个数字参数，虚机配置起始ID和结束ID")
    #     sys.exit(1)
    # for i in range(int(sys.argv[1]),int(sys.argv[2])+1):
    rgs = [range(1201,1207),range(2201,2207),range(3201,3207)]
    for k in rgs:
        for i in k:
            # print('go print {}'.format(i))
            # with open('/etc/pve/nodes/{}/qemu-server/{}.conf'.format(hostname, i), "r") as f:
            #     cf = f.read()
            # with open('/etc/pve/nodes/{}/qemu-server/{}.conf'.format(hostname, i), "w") as f:
                # print('---------------------------------------------')
                # print(cf)
                # print('----------------------------------------------')
            dt = re.search(r'[^~]*virtio=([\w:]+),[^~]*?serial=([\w]+),[^~]*?(smbios1[^\n]*)',cf)
            cfg_r[i] = dict(
                mac = randmac(dt.groups()[0][:2]),
                hd_id='CVCV{}LB120BGN'.format(''.join(random.sample("0123456789", 8))),
                uuid = str(uuid.uuid4()),
                sim_serial=''.join(random.sample("0123456789abcdef", 7)).upper(),
            )
            cfg_r[i]['simbios_str'] = 'smbios1: base64=1,manufacturer=RGVsbCBJbmM=,product=UG93ZXJFZGdlIFI3MjB4ZA==,serial={},uuid={},version=Tm90IFNwZWNpZmllZA=='\
                .format(base64.b64encode(cfg_r[i]['sim_serial'].encode()).decode(),cfg_r[i]['uuid'])
            cf = cf.replace(dt.groups()[0], cfg_r[i]['mac'])
            cf = cf.replace(dt.groups()[1], cfg_r[i]['hd_id'])
            cf = cf.replace(dt.groups()[2], cfg_r[i]['simbios_str'])
            # f.write(cf)

    with open('vm_conf_chg.json','w') as f:
        json.dump(cfg_r, f, indent=1)
    print(cfg_r)
    print('生成完毕')
